package cn.achao.csr.zfb.controller;

import cn.achao.csr.api.model.resp.AliLoginResp;
import cn.achao.csr.api.model.resp.AliUserInfoResp;
import cn.achao.csr.base.constant.AliConstants;
import cn.achao.csr.base.constant.Constants;
import cn.achao.csr.base.constant.enums.SysSourceEnum;
import cn.achao.csr.base.exception.BusinessException;
import cn.achao.csr.base.resp.R;
import cn.achao.csr.base.utils.ThrowUtils;
import cn.achao.csr.security.annotation.InnerAuth;
import cn.achao.csr.zfb.core.config.AliConfigProperties;
import cn.achao.csr.zfb.service.AliLoginService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

/**
 * @Author: achao
 **/
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/zfb")
public class ZfbLoginController {

    private final AliConfigProperties.CsrAlipayConfig csrAlipayConfig;
    private final AliLoginService aliLoginService;

    @InnerAuth
    @GetMapping("/zfbLogin")
    public R<?> zfbLogin(@RequestParam("status") String status) {
        AliLoginResp resp = new AliLoginResp();
        try {
            String appId = csrAlipayConfig.getAppId();
            String authCodeUrl = csrAlipayConfig.getAuthCodeUrl();
            String callBackUrl = URLEncoder.encode(csrAlipayConfig.getAuthCodeCallbackUrl(), Constants.UTF8);
            String url = String.format(authCodeUrl, appId, AliConstants.AUTH_USER, status, callBackUrl);
            resp.setUrl(url);
        } catch (UnsupportedEncodingException e) {
            ThrowUtils.throwIf(BusinessException.fail("回调编码失败", SysSourceEnum.CSR_ZFB.getSysName()));
        }
        return R.ok(resp);
    }

    /**
     * 支付宝回调
     * @param app_id
     * @param source
     * @param auth_code
     * @param state 自定义参数
     * @return
     */
    @GetMapping("/callBack")
    public String callBack(String app_id, String source, String auth_code, String state,
                           HttpServletResponse response) {
        log.info("支付宝回调 appId【{}】,source【{}】,authCode【{}】", app_id, source, auth_code);
        AliUserInfoResp.AlipayUserInfoShareResponseDTO userInfo = aliLoginService.getUserInfo(auth_code);
        R<?> r = aliLoginService.notifyAuth(userInfo, state);
        if (R.isSuccess(r)) {
            try {
                Map<String, Object> data = (Map<String, Object>) r.getData();
                String token = (String) data.get("access_token");
                response.sendRedirect("http://localhost:8080?token=" + token);
            } catch (IOException e) {
                log.error("callBack回调失败{}", e);
                throw new RuntimeException(e);
            }

        }
        return "";
    }
}
